<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of AuthorizationPlugin
 *
 * @author JeyDotC
 * 
 * @export Plugins
 */
class AuthorizationPlugin extends UnderscorePlugin implements BeforeTask {

    public function beforeTask($task) {
        $request = ModulesContext::instance()->getRequest();
        $session = $request->getSession();
        
        if (!$session->state() === SessionStates::ACTIVE || !$this->checkRoles()) {
            $returnUrl = $request->getURI();
            $router = ModulesContext::instance()->getRouting();
            //This is a joomla specific action.
            $url = $this->getOnPermissionDeniedURL() . "&return=" . base64_encode($returnUrl);
            $router->redirect($url);
        }

        return true;
    }

    private function getOnPermissionDeniedURL() {
        return ModulesContext::instance()->getConfig()->get("PermissionDeniedURL");
    }

    private function retreiveRequiredRoles() {
        $module = $this->getModule();
        $roles = array();
        $annotations = $module->getMetadata();

        if ($annotations->has("RequiredRoles")) {
            $roles = explode(":", $annotations->find("RequiredRoles"));
        }

        return $roles;
    }

    private function checkRoles() {
        $result = true;
        $requiredRoles = $this->retreiveRequiredRoles();
        
        if (count($requiredRoles) > 0) {
            $user = ModulesContext::instance()->getCurrentUser();
            $roles = $user->getPermissions();
            
            $coincidences = array_intersect($roles, $requiredRoles);
            if (count($coincidences) == 0) {
                $result = false;
            }
        }

        return $result;
    }

}

?>
